package com.example.yjhero.safeapp.utils;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.widget.Toast;
import com.example.yjhero.safeapp.R;
import com.example.yjhero.safeapp.activity.HomeActivity;
import com.example.yjhero.safeapp.entities.VersionEntity;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class VersionUpdateUtils {
    // 状态码
    private static final int MESSAGE_NET_EEOR = 101;
    private static final int MESSAGE_IO_EEOR = 102;
    private static final int MESSAGE_JSON_EEOR = 103;
    private static final int MESSAGE_SHOEW_DIALOG = 104;
    protected static final int MESSAGE_ENTERHOME = 105;

    // 对话框
    private ProgressDialog mProgressDialog;
    private Activity mContext;
    private String mVersion;
    private VersionEntity mVersionEntity;

    public VersionUpdateUtils(Activity mContext, String mVersion) {
        this.mContext = mContext;
        this.mVersion = mVersion;
        mVersionEntity =new VersionEntity();
    }

    // 在 UI 线程中 更新界面.将进程写入Util
    private Handler mHandler =new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case MESSAGE_NET_EEOR:
                    Toast.makeText(mContext,"网络异常",Toast.LENGTH_SHORT).show();
                    break;
                case MESSAGE_IO_EEOR:
                    Toast.makeText(mContext,"服务器异常",Toast.LENGTH_SHORT).show();
                    enterHome();
                    break;
                case MESSAGE_JSON_EEOR:
                    Toast.makeText(mContext,"json解析异常",Toast.LENGTH_SHORT).show();
                    break;
                case MESSAGE_SHOEW_DIALOG:
                    showUpdateDialog(mVersionEntity.mDes);
                    break;
                case  MESSAGE_ENTERHOME:
                    Intent intent=new Intent(mContext,HomeActivity.class);
                    mContext.startActivity(intent);
                    mContext.finish();
                    break;
            }
        }
    };


    private void showUpdateDialog(String mDes){
         AlertDialog.Builder builder=new AlertDialog.Builder(mContext);
         builder.setTitle("检查到新版本!!!"+mVersionEntity.mCode);
         builder.setCancelable(false);
         builder.setIcon(R.drawable.ic_launcher);

         builder.setPositiveButton("立即升级", new DialogInterface.OnClickListener() {
             @Override
             public void onClick(DialogInterface dialog, int which) {
                initProgressDialog();
                Toast.makeText(mContext,"正在更新...",Toast.LENGTH_SHORT).show();
             }
         });

         builder.setNegativeButton("暂不升级", new DialogInterface.OnClickListener() {
             @Override
             public void onClick(DialogInterface dialog, int which) {
                 dialog.dismiss();
                 enterHome();
             }
         });
         builder.show();
    }

    private void enterHome() {
        mHandler.sendEmptyMessageDelayed(MESSAGE_ENTERHOME,1500);
    }

    private void initProgressDialog() {
        mProgressDialog=new ProgressDialog(mContext);
        mProgressDialog.setMessage("准备下载...");
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mProgressDialog.show();
    }


    /**
     * 检测并获取服务器更新
     */
    public void getCloudVersion() {
        new Thread(new Runnable() {
            @Override
            public void run() {//匿名方法(java也支持匿名方法)
                try {
                    URL url = new URL("http://10.0.2.2:8080/updateinfo.html");
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setConnectTimeout(5000);
                    connection.setReadTimeout(5000);
                    connection.setRequestMethod("GET");

                    InputStream in = connection.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                    StringBuilder response = new StringBuilder();

                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    String result = response.toString();
                    JSONObject json = new JSONObject(result);

                    mVersionEntity.mCode = json.getString("code");
                    mVersionEntity.mDes= json.getString("des");
                    mVersionEntity.apkurl = json.getString("apkurl");

                    if (!TextUtils.equals(mVersion, mVersionEntity.mCode)) {

                        mHandler.sendEmptyMessage(MESSAGE_SHOEW_DIALOG);
                    }

                } catch (MalformedURLException e) {
                    // 网络有问题
                    mHandler.sendEmptyMessage(MESSAGE_NET_EEOR);
                    e.printStackTrace();
                } catch (IOException e) {
                    // 服务器出错
                    mHandler.sendEmptyMessage(MESSAGE_IO_EEOR);
                    e.printStackTrace();
                } catch (JSONException e) {
                    // 解析出错
                    mHandler.sendEmptyMessage(MESSAGE_JSON_EEOR);
                    e.printStackTrace();
                }
            }
        }).start();

    }
}